package com.secure.context;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.secure.annotation.ApiSecure;
import org.springframework.context.ApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ApplicationContextHolder {

    private static ApplicationContext applicationContext;
    private static Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = new HashMap<>();
    private static List<String> handerMethodPathList = new ArrayList<>();
    private static List<String> annotationApiSecurePathList = new ArrayList<>();

    public static void setRequestMappingHandlerMapping(RequestMappingHandlerMapping requestMappingHandlerMapping) {
        filterApiSecureServletPathList(requestMappingHandlerMapping);
    }

    public static List<String> getHanderMethodPathList() {
        return handerMethodPathList;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static void setApplicationContext(ApplicationContext applicationContext) {
        ApplicationContextHolder.applicationContext = applicationContext;
    }

    public static List<String> getAnnotationApiSecurePathList() {
        return annotationApiSecurePathList;
    }

    public static Map<RequestMappingInfo, HandlerMethod> getHandlerMethodMap() {
        return handlerMethodMap;
    }

    /**
     * 过滤需要api安全校验的处理器方法路径
     *
     * @param requestMappingHandlerMapping
     */
    private static void filterApiSecureServletPathList(RequestMappingHandlerMapping requestMappingHandlerMapping) {
        if (ObjectUtil.isNotNull(requestMappingHandlerMapping)) {
            Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();
            if (CollectionUtil.isNotEmpty(handlerMethods)) {
                handlerMethodMap = handlerMethods;
                for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
                    RequestMappingInfo requestMappingInfo = entry.getKey();
                    HandlerMethod handlerMethod = entry.getValue();
                    handerMethodPathList.addAll(requestMappingInfo.getPatternValues());
                    if (handlerMethod.hasMethodAnnotation(ApiSecure.class)) {
                        annotationApiSecurePathList.addAll(requestMappingInfo.getPatternValues());
                    }
                }
            }
        }
    }

}
